package com.it.admin.utils;

import com.it.admin.config.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioProperties minioProperties;


    public String uploadFile(MultipartFile file) throws Exception {
        // 判断文件是否为空
        if (file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常：文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }


        // 文件的原始名称
        String originalFileName = file.getOriginalFilename();

        String filePath = MinioUtil.builderFilePath(originalFileName);

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName()).object(filePath).stream(file.getInputStream(),file.getSize(),-1).build());

        // 返回文件的访问链接
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), filePath);
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        return url;
    }

    public static String builderFilePath(String fileName){
        //根据日期生成路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //后缀和文件后缀一致
        int index = fileName.lastIndexOf(".");
        // test.jpg -> .jpg
        String fileType = fileName.substring(index);

        return new StringBuilder().append(datePath).append(uuid).append(fileType).toString();
    }

}
